import scipy.misc
import scipy.ndimage
import numpy as np
from celery import Celery, task
from logging import debug, info, error, warning
import numpy as np
import coloredlogs
import logging
from PIL import Image
import pytesseract
from MA.watcher import ModuleWatcher
import tesserocr
import pbcvt
import matplotlib.pyplot as plt


def imread(image_path, resize=False):
    img = scipy.misc.imread(image_path)
    if resize:
        # if img.ndim == 2:
        #     size = [int(img.shape[0]/3), int(img.shape[1]/3)]
        # elif img.ndim == 3:
        #     size = [[int(img.shape[0]/3), int(img.shape[1]/3)], img.shape[2]]
        # else:
        #     raise Exception('Error size')
        img = scipy.misc.imresize(img, 0.33)
    return img / 255


# @app.tasks
def get_mask(image: np.array):
    """
    :param image: images with intensity 0~~1
    :return: binary image
    """
    if image.ndim == 3:
        image = image[:, :, 1]  # extract green channel
    mask = 1 - (image < 0.06)
    return scipy.ndimage.binary_erosion(mask, np.ones((11, 11)), 10)


def get_exclude(original_image):
    """
    :param original_image: image with intensity 0~~1
    :return:
    """
    # original_image = imread(image_path)
    mask_image = get_mask(original_image)
    # pbcvt.vesselseg(original_image,10)
    result = pbcvt.exudate_extract((original_image * 255).astype(np.uint8))
    return {
        'result', result,
        'original', original_image,
    }


def readInfo(original_image):
    # try:
    id_pil = Image.fromarray(
        (original_image[0:130, 0:430, :] * 255).astype(np.uint8),
        mode='RGB').resize((100, 30))
    id_np = np.array(id_pil)
    # plt.imshow(id_np)
    # plt.show()
    name_pil = Image.fromarray(
        (original_image[130:300, 0:500, :] * 255).astype(np.uint8),
        mode='RGB').resize((213, 80))
    date_pil = Image.fromarray(
        (original_image[0:400, 3200:, :] * 255).astype(np.uint8),
        mode='RGB')
    which_eye_pil = original_image[2280:2440, 3700:, 1]
    # which_eye_pil.show('afds')
    pid = tesserocr.image_to_text(id_pil).strip()
    if len(pid) != 5:
        pid = ''
    pname = tesserocr.image_to_text(name_pil, lang='chi_sim').strip()
    pdata = tesserocr.image_to_text(date_pil).strip().replace('/', '_')
    which_eye = 'R' if which_eye_pil[100][100] > 0.5 else 'L'

    result = {
        'name': pname,
        'date': pdata,
        'id': pid,
        'which_eye': which_eye,
    }
    return result
    # except Exception as e:
    #     logging.exception(e)
    #     return {
    #         'name': '',
    #         'date': '',
    #         'id': '',
    #         'which_eye': '',
    #     }



if __name__ == '__main__':
    coloredlogs.install(level='DEBUG', logger=logging.getLogger(),
                        fmt='%(filename)s:%(lineno)d %(message)s',
                        datefmt='%H:%M:%S',
                        )

    img = imread('/home/d/data/rawdata/000010867286595.jpg')
    readInfo(img)
